﻿using AutoMapper;
using B.S.Sterilizationcenter.Domain.yjb;
using B.S.Sterilizationcenter.Domain.zmc;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Read.API.Appliaction.Commends.yjb;
using B.S.Sterilizationcenter.Read.API.Appliaction.Commends.zmc;
using B.S.Sterilizationcenter.Read.API.Dto;
using MediatR;
using SqlSugar;

namespace B.S.Sterilizationcenter.Read.API.Appliaction.CommandHandlers.yjb
{
    public class ConsumTypeTreeCommandHandlers : IRequestHandler<ConsumTypeTreeCommand, ApiResult<List<ConsumTypeTreeDTO>>>
    {

        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public ConsumTypeTreeCommandHandlers(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        /// <summary>
        /// 树状显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<ConsumTypeTreeDTO>>> Handle(ConsumTypeTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<ConsumTypeTreeDTO>> result = new ApiResult<List<ConsumTypeTreeDTO>>();
            result.Code = ApiEnums.查询成功;
            result.Msg = "查询器械分类树状结构成功";
            result.Data = GetTree(0);
            return Task.FromResult(result);
        }

        public List<ConsumTypeTreeDTO> GetTree(int api)
        {
            var list = db.Queryable<ConsumType>().Where(it => it.Cid == api).ToList();
            var res = new List<ConsumTypeTreeDTO>();
            foreach (var item in list)
            {
                var model = new ConsumTypeTreeDTO()
                {
                    value = item.ConsumTypeId,
                    label = item.ConsumTypeTypeName,
                    children=GetTree(item.ConsumTypeId)
                };
                res.Add(model);
            }
            return res;
        }
    }
}
